package com.lvcoding.cloud.common.security.config;

import com.lvcoding.cloud.common.security.auth.CommonUserConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.stereotype.Component;

/**
 * @Description 资源服务器配置
 * @Date 2020-07-15 3:49 下午
 * @Author wuyanshen
 */
@Component
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private UserAuthenticationConverter userAuthenticationConverter;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenServices(this.tokenServices());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //下面地址 不需要通过oauth2登录授权
                .antMatchers("/user/info/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    public ResourceServerTokenServices tokenServices() {
        DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
        tokenConverter.setUserTokenConverter(userAuthenticationConverter);
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl("http://localhost:8000/oauth/check_token");
        services.setClientId("app");
        services.setClientSecret("app");
        //将用户信息解析到SpringSecurity安全上下文
        services.setAccessTokenConverter(tokenConverter);
        return services;
    }

    @Bean
    public UserAuthenticationConverter userAuthenticationConverter(){
        return new CommonUserConverter();
    }
}
